<template>
  <div>
    <!-- 搜索 -->
    <div class="search">
      <el-input placeholder="请输入公告标题" clearable v-model="queryInfo.title"></el-input>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>

    <!-- 工具栏 -->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
      <el-button type="danger" @click="delBatch">批量删除 <i class="el-icon-remove-outline"></i></el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="55"></el-table-column>
      <el-table-column prop="title" label="公告标题" show-overflow-tooltip></el-table-column>
      <el-table-column label="封面" width="122">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.img"
            :preview-src-list="[scope.row.img]"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="hits" label="浏览量" width="80"></el-table-column>
      <el-table-column prop="introduce" label="公告详情" width="200">
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="view(scope.row.introduce)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="公告时间" width="160"></el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleEdit(scope.row.id)">编辑 <i class="el-icon-edit"></i></el-button>
          <el-button type="danger" @click="del(scope.row.id)">删除 <i class="el-icon-remove-outline"></i></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="padding: 10px 0">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum" :page-sizes="[2, 5, 10, 20]" :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 添加/修改对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="60%" :close-on-click-modal="false"
      @close="handleDialogClose">
      <el-form label-width="140px" size="small" style="width: 85%;" :model="form" :rules="rules" ref="dialogForm">
        <el-form-item prop="title" label="公告标题">
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="img" label="封面">
          <image-upload v-model="form.img" ref="imageUpload"></image-upload>
        </el-form-item>
        <el-form-item prop="introduce" label="公告详情">
          <mavon-editor ref="md" v-model="form.introduce" :toolbars="toolbars" style="min-height: 400px;" @imgAdd="imgAdd"></mavon-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="公告详情" :visible.sync="detailVisible" width="60%" :close-on-click-modal="false">
      <mavon-editor
          class="md"
          :value="detailContent"
          :subfield="false"
          :defaultOpen="'preview'"
          :toolbarsFlag="false"
          :editable="false"
          :scrollStyle="true"
          :ishljs="true"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload.vue'
import { mavonEditor } from 'mavon-editor'
import axios from "axios"
export default {
  name: "Article",
  components: {
    ImageUpload,
    mavonEditor
  },
  data() {
    return {
      // 表格数据
      tableData: [],
      // 总条数
      total: 0,
      // 查询条件
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
      },
      // 表单数据
      form: {
        hits: 0,
        img: "",
      },
      // mavon-editor工具栏配置
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
      },
      // 对话框标题
      dialogTitle: "",
      // 对话框是否显示
      dialogFormVisible: false,
      // 批量选择
      multipleSelection: [],
      // 用户信息
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      // 详情对话框相关
      detailVisible: false,
      detailContent: '',
      // 校验规则
      rules: {
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' }
        ],
        hits: [
          { required: true, message: '请输入浏览量', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入公告详情', trigger: 'blur' }
        ],
      },

    }
  },
  created() {
    this.load()
  },
  methods: {
    // 加载数据
    load() {
      // 加载公告
      this.request.get("/article/page", {
        params: this.queryInfo
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })

    },
    // 添加
    handleAdd() {
      this.dialogTitle = "添加公告"
      this.dialogFormVisible = true
    },
    // 修改
    async handleEdit(id) {
      const res = await this.request.get("/article/" + id)
      this.form = res.data
      this.dialogTitle = "修改公告"
      this.dialogFormVisible = true
    },
    // 保存
    save() {
      this.$refs.dialogForm.validate(async valid => {
        if (!valid) {
          return
        }
        const res = await this.request.post("/article", this.form)
        if (res.code !== 200) {
          return this.$message.error(res.msg)
        }
        this.$message.success("保存成功")
        this.dialogFormVisible = false
        this.load()
      })
    },
    // 删除
    del(id) {
      this.$confirm('是否确定删除该数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 删除
          const res = await this.request.delete("/article/" + id)
          if (res.code !== 200) {
            return this.$message.error("删除失败：" + res.msg)
          }
          this.$message.success("删除成功")
          // 判断当前页最后一条数据
          if (this.tableData.length === 1 && this.queryInfo.pageNum > 1) {
            this.queryInfo.pageNum--
          }
          // 重新加载数据
          this.load()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 批量选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 批量删除
    delBatch() {
      if (this.multipleSelection.length == 0) {
        this.$message.error("请选择需要删除的数据")
        return
      }
      this.$confirm('是否确定删除该数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 删除
          let ids = this.multipleSelection.map(item => item.id)
          const res = await this.request.delete("/article/del/batch", { data: ids })
          if (res.code !== 200) {
            return this.$message.error("批量删除失败：" + res.msg)
          }
          this.$message.success("删除成功")
          // 判断当前页最后一条数据
          if (this.tableData.length === ids.length && this.queryInfo.pageNum > 1) {
            this.queryInfo.pageNum--
          }
          // 重新加载数据
          this.load()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 重置
    reset() {
      this.queryInfo = {
        pageNum: 1,
        pageSize: 5
      }
      this.load()
    },
    // 监听页大小改变
    handleSizeChange(pageSize) {
      this.queryInfo.pageSize = pageSize
      this.load()
    },
    // 监听页码改变
    handleCurrentChange(pageNum) {
      this.queryInfo.pageNum = pageNum
      this.load()
    },
    // 文件上传成功的回调
    handleFileUploadSuccess(res) {
      this.form.file = res
    },
    // 下载
    download(url) {
      window.open(url)
    },
    // 导出
    exp() {
      window.open("http://localhost:7777/article/export")
    },
    // 导入
    handleExcelImportSuccess() {
      this.$message.success("导入成功")
      this.load()
    },
    // 查看公告详情
    view(content) {
      this.detailContent = content
      this.detailVisible = true
    },
    // 对话框关闭
    handleDialogClose() {
      this.dialogFormVisible = false
      this.form = {};
      this.$refs.dialogForm.resetFields() // 重置表单
      if (this.$refs.imageUpload) {
        this.$refs.imageUpload.clearFiles();
      }
      if (this.$refs.file) {
        this.$refs.file.clearFiles();
      }
    },
    // 绑定富文本编辑器图片上传事件
    imgAdd(pos, $file) {
      let $vm = this.$refs.md
      // 第一步.将图片上传到服务器
      const formData = new FormData();
      formData.append('file', $file);
      axios({
        url: 'http://localhost:7777/file/upload',
        method: 'post',
        data: formData,
        headers: {'Content-Type': 'multipart/form-data'},
      }).then((res) => {
        // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
        $vm.$img2Url(pos, res.data);
      })
    },
  }
}
</script>

<style scoped style="less">
/* mavon-editor详情页面样式 */
.md {
  font-size: 14px;
  line-height: 1.8;
  color: #333;

  /* 标题样式 */
  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    margin-top: 24px;
    margin-bottom: 16px;
    font-weight: 600;
    line-height: 1.25;
  }

  /* 段落样式 */
  p {
    margin-top: 0;
    margin-bottom: 16px;
  }

  /* 列表样式 */
  ul,
  ol {
    padding-left: 2em;
    margin-top: 0;
    margin-bottom: 16px;

    ul,
    ol {
      margin-top: 0;
      margin-bottom: 0;
    }
  }

  /* 引用样式 */
  blockquote {
    padding: 0 1em;
    color: #6a737d;
    border-left: 0.25em solid #dfe2e5;
    margin: 16px 0;
  }

  /* 代码样式 */
  code {
    padding: 0.2em 0.4em;
    margin: 0;
    font-size: 85%;
    background-color: rgba(27,31,35,0.05);
    border-radius: 3px;
    font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
  }

  pre {
    padding: 16px;
    overflow: auto;
    font-size: 85%;
    line-height: 1.45;
    background-color: #f6f8fa;
    border-radius: 3px;
    margin-top: 0;
    margin-bottom: 16px;
    font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
  }

  /* 图片样式 */
  img {
    max-width: 100%;
    box-sizing: content-box;
    background-color: #fff;
    margin: 16px 0;
  }
}

.search {
  margin: 10px 0;

  .el-input {
    width: 150px;
    margin-right: 10px;
  }

  .el-select {
    width: 140px;
    margin-right: 10px;
  }
}

.headerBg {
  background: #eee !important;
}
</style>